//
//  GFDetialsViewController.m
//  GoodFood
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFDetialsViewController.h"

@interface GFDetialsViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *detailsTableView;
@property (nonatomic, strong) GFDetialsModel *deModel;
@property (nonatomic, strong) GFDetialUnitModel *deUnModel;

/* 向制作界面传网址 */
@property (nonatomic, copy) NSString *urlStr;

@property (nonatomic, strong) NSMutableArray *unArr;

/* 用作收藏的数组 */
@property (nonatomic, strong) NSArray *collectArr;

/* 接收搜索的数组时使用*/
@property (nonatomic, strong) NSMutableArray *arr;



/* 提示收藏 */
@property (nonatomic, strong) UIAlertController *alertCon;

@end

@implementation GFDetialsViewController

- (void)viewWillAppear:(BOOL)animated {
    /* 改变navigationBar的颜色 */
    
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    
    view.backgroundColor = [UIColor colorWithRed:190 / 255.0 green:231 / 255.0 blue:233 / 255.0 alpha:1];
    
    view.hidden = NO;
    
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:209/255.0 green:186/255.0 blue:116/255.0 alpha:1];
    
#pragma mark - 修改navi颜色
    /* 修改navigation title 颜色 */
    
    UIColor *color = [UIColor colorWithRed:209/255.0 green:186/255.0 blue:116/255.0 alpha:1];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];/* 在NSFontAttributeName中寻找*/
    
    self.navigationController.navigationBar.titleTextAttributes = dic;
    
    self.navigationController.navigationBarHidden = NO;
    

}

#pragma mark _ 处理数据
- (void)handleData {
    
    NSString *str = @"http://food.boohee.com/fb/v1/foods/";
    
    //    NSLog(@"%@", self.food_code);
    
    self.urlStr = [str stringByAppendingString:self.food_code];
    
    [AFNetHandle GETWithURL:self.urlStr body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        self.deModel = [GFDetialsModel detailsModelWithDintionary:result];
        
        
        self.unArr = [NSMutableArray array];
        
        
        for (NSDictionary *dic in self.deModel.units) {
            
            self.deUnModel = [GFDetialUnitModel modWithDic:dic];
            
            [self.unArr addObject:self.deUnModel];
        }
        
        //        NSLog(@"--------%@", self.deModel.name);
        self.title = self.deModel.name;
        
        [self.detailsTableView reloadData];
        [self.overTimeView removeFromSuperview];
        [self.waitView removeFromSuperview];
        
    } fail:^(NSError *error) {
        [self.overTimeView removeFromSuperview];
        self.overTimeView = [[GFOverTimeView alloc] initWithFrame:self.view.frame withButtonBlock:^(UIButton *button) {
            [self.view addSubview:self.waitView];
            [self handleData];
        }];
        [self.waitView removeFromSuperview];
        [self.view addSubview:self.overTimeView];
        
    }];
}



#pragma mark _ 创建tableView
- (void)creatDetailsTableView {
    
    self.detailsTableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.detailsTableView.delegate = self;
    self.detailsTableView.dataSource = self;
    [self.view addSubview:self.detailsTableView];
    
    /* 重用池 */
    [self.detailsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    [self.detailsTableView registerClass:[FirstCell class] forCellReuseIdentifier:@"FirstCell"];
    [self.detailsTableView registerClass:[EvaluateCell class] forCellReuseIdentifier:@"EvaluateCell"];
    [self.detailsTableView registerClass:[RecipeCell class] forCellReuseIdentifier:@"RecipeCell"];
    [self.detailsTableView registerClass:[EqualCell class] forCellReuseIdentifier:@"EqualCell"];
    [self.detailsTableView registerClass:[UnitsCell class] forCellReuseIdentifier:@"UnitsCell"];
    [self.detailsTableView registerClass:[LastCell class] forCellReuseIdentifier:@"LastCell"];
    

}



#pragma mark _ tableView的DataSource协议方法
/* 分区数 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.deModel.units.count == 0 && self.deModel.compare.count == 0) {
        return 3;
    } else {
        return 4;
    }
}

/* 每区的行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.deModel.units.count == 0 && self.deModel.compare.count == 0) {
        if (section == 0) {
            return 1;
        } else if (section == 1) {
            if (self.deModel.recipe == YES) {
                return 2;
            } else {
                return 1;
            }
        } else {
            return 6;
        }
    } else {
        if (section == 0) {
            return 1;
        } else if (section == 1) {
            if (self.deModel.recipe == YES) {
                return 2;
            } else {
                return 1;
            }
        } else if (section == 2) {
            if (self.deModel.units.count == 0) {
                return 1;
            } else if (self.deModel.compare.count == 0) {
                return self.unArr.count;
            } else {
                return self.unArr.count + 1;
            }
        } else {
            return 6;
        }
    }
}

/* cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (self.deModel.units.count == 0 && self.deModel.compare.count == 0) {
        if (indexPath.section == 0) {
            FirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstCell"];
            cell.deModel = self.deModel;
            return cell;
        } else if (indexPath.section == 1) {
            if (self.deModel.recipe == YES) {
                if (indexPath.row == 0) {
                    EvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluateCell"];
                    cell.deModel = self.deModel;
                    return cell;
                } else {
                    RecipeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecipeCell"];
                    cell.deModel = self.deModel;
                    return cell;
                }
            } else {
                EvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluateCell"];
                cell.deModel = self.deModel;
                return cell;
            }
        } else {
            if (indexPath.row == 5) {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
                cell.textLabel.text = @"查看更多营养信息";
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.textLabel.textColor = [UIColor lightGrayColor];
                cell.textLabel.textAlignment = NSTextAlignmentCenter;

                return cell;
            } else {
                LastCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LastCell"];
                cell.deModel = self.deModel;
                cell.rowNumber = indexPath.row;
                return cell;
            }
        }
    } else {
        if (indexPath.section == 0) {
            FirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstCell"];
            cell.deModel = self.deModel;
            return cell;
        } else if (indexPath.section == 1) {
            if (self.deModel.recipe == YES) {
                if (indexPath.row == 0) {
                    EvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluateCell"];
                    cell.deModel = self.deModel;
                    return cell;
                } else {
                    RecipeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecipeCell"];
                    cell.deModel = self.deModel;
                    return cell;
                }
            } else {
                EvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluateCell"];
                cell.deModel = self.deModel;
                return cell;
            }
        }else if (indexPath.section == 2) {
            if (self.deModel.units.count == 0) {
                EqualCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EqualCell"];
                cell.deModel = self.deModel;
                return cell;
            } else if (self.deModel.compare.count == 0) {
                UnitsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UnitsCell"];
                cell.deUnModel = self.unArr[indexPath.row];
                return cell;
            } else {
                if (indexPath.row == 0) {
                    EqualCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EqualCell"];
                    cell.deModel = self.deModel;
                    return cell;
                } else {
                    UnitsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UnitsCell"];
                    cell.deUnModel = self.unArr[indexPath.row - 1];
                    return cell;
                }
            }
        }else {
            if (indexPath.row == 5) {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
                cell.textLabel.text = @"查看更多营养信息";
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.textLabel.textColor = [UIColor lightGrayColor];
                cell.textLabel.textAlignment = NSTextAlignmentCenter;

                return cell;
            } else {
                LastCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LastCell"];
                cell.deModel = self.deModel;
                cell.rowNumber = indexPath.row;
                return cell;
            }
        }
    }
}

/* cell高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat x = [GFCalculateWidthOrHeigth stringHeight:self.deModel.appraise withWidth:ScreenWidth - ScreenWidth / 375.0 * 120 withFontDictionary:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
    CGFloat h;
    if (x < ScreenWidth / 375.0 * 120) {
        h = ScreenWidth / 375.0 * (120 + 20);
    } else {
        h = ScreenWidth / 375.0 * (x + 60);
    }
    
    
    if (self.deModel.units.count == 0 && self.deModel.compare.count == 0) {
        if (indexPath.section == 0) {
            return ScreenWidth / 375.0 * 100;
        } else if (indexPath.section == 1) {
            if (self.deModel.recipe == YES) {
                if (indexPath.row == 0) {
                    return h;
                } else {
                    return ScreenWidth / 375.0 * 50;
                }
            } else {
                return h;
            }
        } else {
            return ScreenWidth / 375.0 * 50;
        }
    } else {
        if (indexPath.section == 0) {
            return ScreenWidth / 375.0 * 100;
        } else if (indexPath.section == 1) {
            if (self.deModel.recipe == YES) {
                if (indexPath.row == 0) {
                    return h;
                } else {
                    return ScreenWidth / 375.0 * 50;
                }
            } else {
                return h;
            }
        } else if (indexPath.section == 2) {
            if (self.deModel.units.count == 0) {
                return ScreenWidth / 375.0 * 100;
            } else if (self.deModel.compare.count == 0) {
                return ScreenWidth / 375.0 * 50;
            } else {
                if (indexPath.row == 0) {
                    return ScreenWidth / 375.0 * 100;
                } else {
                    return ScreenWidth / 375.0 * 50;
                }
            }
        } else {
            return ScreenWidth / 375.0 * 50;
        }
    }
}

/* headView高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return ScreenWidth / 375.0 * 50;
    }
}



#pragma mark _ tableView Delegate 协议方法
/* headView内容 */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (self.deModel.units.count == 0 && self.deModel.compare.count == 0) {
        if (section == 1) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 375.0 * 50)] ;
            view.backgroundColor = [UIColor colorWithRed:237 / 255.0 green:237 / 255.0 blue:237 / 255.0 alpha:1];
            GFBaseLabel *label = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 20, ScreenWidth, ScreenWidth / 375.0 * 20)];
            label.text = @"趣·评价";
            [view addSubview:label];
    
            return view;
        } else {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 375.0 * 50)];
            view.backgroundColor = [UIColor colorWithRed:237 / 255.0 green:237 / 255.0 blue:237 / 255.0 alpha:1];
            GFBaseLabel *label1 = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 100, ScreenWidth / 375.0 * 20)];
            GFBaseLabel *label2 = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 190, ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 100, ScreenWidth / 375.0 * 20)];
            GFBaseLabel *label3 = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 300, ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 75, ScreenWidth / 375.0 * 20)];
            label1.text = @"营养元素";
            label2.text = @"每100克";
            label3.text = @"备注";
            
            [view addSubview:label1];
            [view addSubview:label2];
            [view addSubview:label3];
            

            return view;
        }
    } else {
        if (section == 1) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 375.0 * 50)];
            view.backgroundColor = [UIColor colorWithRed:237 / 255.0 green:237 / 255.0 blue:237 / 255.0 alpha:1];
            GFBaseLabel *label = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 20, ScreenWidth, ScreenWidth / 375.0 * 20)];
            label.text = @"趣·评价";
            [view addSubview:label];
            
            
            return view;
        } else if (section == 2) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 375.0 * 50)];
            view.backgroundColor = [UIColor colorWithRed:237 / 255.0 green:237 / 255.0 blue:237 / 255.0 alpha:1];
            GFBaseLabel *label = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 20, ScreenWidth, ScreenWidth / 375.0 * 20)];
            label.text = @"所含热量";
            [view addSubview:label];
           
            return view;
        } else {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 375.0 * 50)];
            view.backgroundColor = [UIColor colorWithRed:237 / 255.0 green:237 / 255.0 blue:237 / 255.0 alpha:1];
            GFBaseLabel *label1 = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 100, ScreenWidth / 375.0 * 20)];
            GFBaseLabel *label2 = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 190, ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 100, ScreenWidth / 375.0 * 20)];
            GFBaseLabel *label3 = [[GFBaseLabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 300, ScreenWidth / 375.0 * 20, ScreenWidth / 375.0 * 75, ScreenWidth / 375.0 * 20)];
            label1.text = @"营养元素";
            label2.text = @"每100克";
            label3.text = @"备注";
            
            [view addSubview:label1];
            [view addSubview:label2];
            [view addSubview:label3];
            
            
            return view;
        }
    }
}

/* 选中cell中内容 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    /* 查看详情跳转 */
    if (indexPath.row == 5) {
        
        GFMoreDetialsViewController *moreVC = [[GFMoreDetialsViewController alloc] init];
        
        moreVC.deModel = self.deModel;
        
        [self.navigationController pushViewController:moreVC animated:YES];
        
    }
    
    /* 原料与做法跳转 */
    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            
            GFMakeDetialsViewController *makeVC = [[GFMakeDetialsViewController alloc] init];
            
            makeVC.frontUrlStr = self.urlStr;
            
            [self.navigationController pushViewController:makeVC animated:YES];
            

            
        }
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatDetailsTableView];
    [self.view bringSubviewToFront:self.waitView];
    /* 创建加载*/

    
    [self handleData];
    
    
    
    
    [[DataBaseHandle shareDataBaseHandle] openDB];
    self.collectArr = [NSArray arrayWithArray:[[DataBaseHandle shareDataBaseHandle] selectFoodDetailsWithFoodName:self.food_code]];
    
    if (self.collectArr.count != 0) {
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"yishoucang"] style:UIBarButtonItemStylePlain target:self action:@selector(collectItem:)];
        self.navigationItem.rightBarButtonItem = item;
        
    } else {
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"weishoucang"] style:UIBarButtonItemStylePlain target:self action:@selector(collectItem:)];
        self.navigationItem.rightBarButtonItem = item;
    }
    // Do any additional setup after loading the view.
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"houtui1"] style:UIBarButtonItemStylePlain target:self action:@selector(backToLastVC:)];
    self.navigationItem.leftBarButtonItem = backItem;
}

#pragma mark - 返回前一个VC
- (void)backToLastVC:(UIBarButtonItem *)item {
    
    
    [self.delegate giveSearchValue:self.searchStr withSearchArr:self.arr withPage:self.pageNum];
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}

- (void)setSearchArr:(NSMutableArray *)searchArr {
    
    
    if (_searchArr != searchArr) {
        
        _searchArr = searchArr;
    }
    
    self.arr = [NSMutableArray arrayWithArray:searchArr];
}


- (void)collectItem:(UIBarButtonItem *)item {
    
    [[DataBaseHandle shareDataBaseHandle] creatTable];
    
    if ([item.image isEqual:[UIImage imageNamed:@"yishoucang"]]) {
        
        self.alertCon = [UIAlertController alertControllerWithTitle:@"提示" message:@"已删除收藏" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:self.alertCon animated:YES completion:^{
            
            [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(closeAlert) userInfo:nil repeats:NO];
            
        }];
        
        
        
        item.image = [UIImage imageNamed:@"weishoucang"];
        
        [[DataBaseHandle shareDataBaseHandle] deleteFoodDetailsWithFoodName:self.food_code];
        
    } else {
        
        self.alertCon = [UIAlertController alertControllerWithTitle:@"提示" message:@"添加收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:self.alertCon animated:YES completion:^{
            
            [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(closeAlert) userInfo:nil repeats:NO];
            
        }];
        
        item.image = [UIImage imageNamed:@"yishoucang"];
        
        [[DataBaseHandle shareDataBaseHandle] insertFoodDetails:self.deModel];
        
        //        NSLog(@"%@", self.deModel.code);
    }
    
    
}

#pragma mark _ 自动关闭alert
- (void)closeAlert {
    
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
